/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2021-2021. All rights reserved.
 */

package com.device.idea.demo.view.widget;

import static com.device.idea.demo.constant.Constant.ILLEGAL_TOUCH_MODE;
import static com.device.idea.demo.constant.Constant.PICKER_COLORS;
import static com.device.idea.demo.constant.Constant.PICKER_COLORS_INDEX_0;
import static com.device.idea.demo.constant.Constant.PICKER_COLORS_INDEX_1;
import static com.device.idea.demo.constant.Constant.PICKER_COLORS_INDEX_2;
import static com.device.idea.demo.constant.Constant.PICKER_COLORS_INDEX_3;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;

import com.device.idea.demo.R;
import com.device.idea.demo.constant.Constant;
import com.device.idea.demo.constant.ToolbarPosition;
import com.device.idea.demo.util.LogUtil;
import com.device.idea.demo.util.MethodUtil;
import com.device.idea.demo.view.WhiteBoardActivity;
import com.device.idea.whiteboard.model.WhiteBoardPen;
import com.device.idea.whiteboard.model.WhiteBoardTouchMode;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 默认的DrawToolbar
 *
 * @since 2021-01-21
 */
public class DrawToolbar extends LinearLayout {
    private static final String TAG = DrawToolbar.class.getSimpleName();

    private static final int POP_WINDOW_HEIGHT = 800;

    private Context mContext;

    private int mCurrentCanvasBgColor = Constant.CANVAS_BACKGROUND_COLOR_BLACK_RGBA;

    private int mCurrentPenColor;

    private int mCurrentPenType;

    private int mCurrentTouchMode = ILLEGAL_TOUCH_MODE;

    private String[] mPenTypes;

    private ClickCallback mCallback;

    private ImageView mDeleteImage;

    private ImageView mPreImage;

    private ImageView mNextImage;

    private TextView mNumTextView;

    private ImageView mNewPageImage;

    private TextView mSaveTextView;

    private TextView mOpenMiddleTex;

    private TextView mThumbnailTextView;

    private ImageView mWhitePenColorImage;

    private ImageView mRedPenColorImage;

    private ImageView mGreenPenColorImage;

    private TextView mPencilTextView;

    private TextView mEraserTextView;

    private TextView mSelectTextView;

    private TextView mCanvasModeTextView;

    private TextView mPreviousTextView;

    private TextView mPosteriorTextView;

    private TextView mSettingTextView;

    private TextView mExitTextView;

    private PenPickerPopWindow mPenPickerPopWindow;

    private EraserPickerPopWindow mEraserPickerPopWindow;

    private SettingPickerPopWindow mSettingPickerPopWindow;

    private MorePopWindow mMorePopWindow;

    private View.OnClickListener mClickListener;

    /**
     * 构造方法
     *
     * @param context 上下文
     */
    public DrawToolbar(@NonNull Context context) {
        this(context, null);
    }

    /**
     * 构造方法
     *
     * @param context 上下文
     * @param attrs attrs
     */
    public DrawToolbar(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    /**
     * 构造方法
     *
     * @param context 上下文
     * @param attrs attrs
     * @param defStyleAttr defStyleAttr
     */
    public DrawToolbar(Context context, AttributeSet attrs, int defStyleAttr) {
        this(context, attrs, defStyleAttr, 0);
    }

    /**
     * 构造方法
     *
     * @param context 上下文
     * @param attrs attrs
     * @param defStyleAttr defStyleAttr
     * @param defStyleRes defStyleRes
     */
    public DrawToolbar(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
        mContext = context;
        initView();
        setOrientation(HORIZONTAL);
    }

    private void initView() {
        View view = LayoutInflater.from(mContext).inflate(R.layout.wbui_horizontal_normal_toolbar_4k, this, true);
        mDeleteImage = view.findViewById(R.id.wbui_toolbar_delete);
        mPreImage = view.findViewById(R.id.wbui_toolbar_last);
        mNextImage = view.findViewById(R.id.wbui_toolbar_next);
        mNumTextView = view.findViewById(R.id.wbui_toolbar_num);
        mNewPageImage = view.findViewById(R.id.wbui_toolbar_add);
        mSaveTextView = view.findViewById(R.id.wbui_toolbar_save);
        mThumbnailTextView = view.findViewById(R.id.wbui_toolbar_more);
        mOpenMiddleTex = view.findViewById(R.id.wbui_toolbar_open);
        mWhitePenColorImage = view.findViewById(R.id.wbui_toolbar_penBlack);
        mRedPenColorImage = view.findViewById(R.id.wbui_toolbar_penRed);
        mGreenPenColorImage = view.findViewById(R.id.wbui_toolbar_penGreen);
        mPencilTextView = view.findViewById(R.id.wbui_toolbar_pencil);
        mEraserTextView = view.findViewById(R.id.wbui_toolbar_eraser);
        mSelectTextView = view.findViewById(R.id.wbui_toolbar_select);
        mCanvasModeTextView = view.findViewById(R.id.wbui_toolbar_canvasMode);
        mPreviousTextView = view.findViewById(R.id.wbui_toolbar_previous);
        mPosteriorTextView = view.findViewById(R.id.wbui_toolbar_posterior);
        mSettingTextView = view.findViewById(R.id.wbui_toolbar_setting);
        mExitTextView = view.findViewById(R.id.wbui_toolbar_exit);
    }

    /**
     * 监听工具来点击事件
     *
     * @param listener 点击事件监听
     */
    @Override
    public void setOnClickListener(View.OnClickListener listener) {
        mClickListener = listener;
        mDeleteImage.setOnClickListener(listener);
        mPreImage.setOnClickListener(listener);
        mNextImage.setOnClickListener(listener);
        mNewPageImage.setOnClickListener(listener);
        mSaveTextView.setOnClickListener(listener);
        mThumbnailTextView.setOnClickListener(listener);
        mOpenMiddleTex.setOnClickListener(listener);
        mWhitePenColorImage.setOnClickListener(listener);
        mRedPenColorImage.setOnClickListener(listener);
        mGreenPenColorImage.setOnClickListener(listener);
        mPencilTextView.setOnClickListener(listener);
        mEraserTextView.setOnClickListener(listener);
        mSelectTextView.setOnClickListener(listener);
        mCanvasModeTextView.setOnClickListener(listener);
        mPreviousTextView.setOnClickListener(listener);
        mPosteriorTextView.setOnClickListener(listener);
        mSettingTextView.setOnClickListener(listener);
        mExitTextView.setOnClickListener(listener);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        int widthSize = MeasureSpec.getSize(widthMeasureSpec);
        int heightSize = MeasureSpec.getSize(heightMeasureSpec);
        LogUtil.debug(TAG, "onMeasure: w=" + widthSize + " h=" + heightSize);
    }

    /**
     * 监听工具来点击事件
     *
     * @param callback 监听事件
     */
    public void setToolbarClickListener(ClickCallback callback) {
        mCallback = callback;
    }

    /**
     * 更新页指示器
     *
     * @param current 当前页
     * @param total 总页数
     */
    public void updateIndicatorView(int current, int total) {
        mNumTextView.setText(getResources().getString(R.string.wb_tool_num, current, total));
        updatePageIndicatorImage(current, total);
    }

    private int getDrawableSize() {
        return getResources().getDimensionPixelSize(R.dimen.dimen_15dp);
    }

    /**
     * 更新上一步view
     *
     * @param isEnabled 是否可用
     */
    public void updatePreView(boolean isEnabled) {
        int resId = isEnabled ? R.drawable.wb_tool_undo : R.drawable.wb_tool_undo_disabled;
        initTextViewDrawable(getDrawableSize(), resId, mPreviousTextView);
        mPreviousTextView.setEnabled(isEnabled);
    }

    /**
     * 更新下一步view
     *
     * @param isEnabled 是否可用
     */
    public void updatePostView(boolean isEnabled) {
        int resId = isEnabled ? R.drawable.wb_tool_redo : R.drawable.wb_tool_redo_disabled;
        initTextViewDrawable(getDrawableSize(), resId, mPosteriorTextView);
        mPosteriorTextView.setEnabled(isEnabled);
    }

    /**
     * 随着颜色的选择，会改变颜色指示器
     *
     * @param color 颜色值
     */
    public void updateCheckedColorView(int color) {
        int resId;
        if (PICKER_COLORS[PICKER_COLORS_INDEX_0] == color) {
            resId = R.drawable.selector_toolbar_pen_white;
            mWhitePenColorImage.setImageResource(resId);
            mWhitePenColorImage.setSelected(true);
            mRedPenColorImage.setSelected(false);
            mGreenPenColorImage.setSelected(false);
        } else if (PICKER_COLORS[PICKER_COLORS_INDEX_1] == color) {
            resId = R.drawable.selector_toolbar_pen_black;
            mWhitePenColorImage.setImageResource(resId);
            mWhitePenColorImage.setSelected(true);
            mRedPenColorImage.setSelected(false);
            mGreenPenColorImage.setSelected(false);
        } else if (PICKER_COLORS[PICKER_COLORS_INDEX_2] == color) {
            mWhitePenColorImage.setSelected(false);
            mRedPenColorImage.setSelected(true);
            mGreenPenColorImage.setSelected(false);
        } else if (PICKER_COLORS[PICKER_COLORS_INDEX_3] == color) {
            mWhitePenColorImage.setSelected(false);
            mRedPenColorImage.setSelected(false);
            mGreenPenColorImage.setSelected(true);
        } else {
            LogUtil.error(TAG, "can not find this color: " + color);
        }
    }

    /**
     * 随着touchmode改变，item背景也会selected
     *
     * @param mode 模式
     */
    public void updateCheckedTouchMode(int mode) {
        if (mCurrentTouchMode != mode) {
            mCurrentTouchMode = mode;
            checkTouchModeView();
        }
    }

    /**
     * 显示笔选择
     *
     * @param pens 笔结构体
     * @param view penView
     */
    public void showPens(View view, WhiteBoardPen[] pens) {
        List<WhiteBoardPen> list = new ArrayList<>(Arrays.asList(pens));
        updateCheckedTouchMode(WhiteBoardTouchMode.TOUCH_MODE_PEN.getValue());
        initPenPickerPopWindow();
        mPenPickerPopWindow.updateData(list, mCurrentPenType);
        mPenPickerPopWindow.show(view, ToolbarPosition.BOTTOM);
    }

    /**
     * 显示更多
     *
     * @param view view
     */
    public void showMore(View view, WhiteBoardActivity whiteBoardActivity) {
        initMorePopWindow(whiteBoardActivity);
        mMorePopWindow.updateWhiteboardInfo();
        mMorePopWindow.show(view, ToolbarPosition.BOTTOM);
    }

    private void initMorePopWindow(WhiteBoardActivity whiteBoardActivity) {
        if (mMorePopWindow == null) {
            mMorePopWindow = new MorePopWindow(getContext(), LayoutParams.WRAP_CONTENT, POP_WINDOW_HEIGHT,
                mClickListener, whiteBoardActivity);
        }
    }

    /**
     * 初始化图标
     */
    public void initDrawableSize(boolean isCanvasLock) {
        int drawableSize = getDrawableSize();
        initTextViewDrawable(drawableSize, R.drawable.wb_pencil_01white, mPencilTextView);
        initTextViewDrawable(drawableSize, R.drawable.wb_tool_eraser, mEraserTextView);
        initTextViewDrawable(drawableSize, R.drawable.wb_tool_select, mSelectTextView);
        initTextViewDrawable(drawableSize, R.drawable.wb_tool_undo_disabled, mPreviousTextView);
        initTextViewDrawable(drawableSize, R.drawable.wb_tool_redo_disabled, mPosteriorTextView);
        initTextViewDrawable(drawableSize, R.drawable.wb_tool_quit, mExitTextView);
        initTextViewDrawable(drawableSize, R.drawable.wb_tool_save, mSaveTextView);
        initTextViewDrawable(drawableSize, R.drawable.wb_tool_save, mThumbnailTextView);
        initTextViewDrawable(drawableSize, R.drawable.wb_tool_open, mOpenMiddleTex);

        // 需要根据Canvas状态初始化TextView显示
        updateCanvasLockState(isCanvasLock);
        initTextViewDrawable(drawableSize, R.drawable.wb_tool_canvas_setting, mSettingTextView);
    }

    private void initTextViewDrawable(int drawableSize, int drawableResId, TextView textView) {
        Drawable initDrawable = getResources().getDrawable(drawableResId, null);
        initDrawable.setBounds(0, 0, drawableSize, drawableSize);
        textView.setCompoundDrawables(null, initDrawable, null, null);
    }

    /**
     * 更新画布（缩放/双人书写）状态
     *
     * @param isCanvasLock 画布状态
     */
    public void updateCanvasLockState(boolean isCanvasLock) {
        int drawableResId;
        int stringResId;
        if (isCanvasLock) {
            drawableResId = R.drawable.wb_tool_canvas_mode_lock;
            stringResId = R.string.double_writing;
        } else {
            drawableResId = R.drawable.wb_tool_canvas_mode_unlock;
            stringResId = R.string.wb_tool_name_canvas_mode;
        }
        initTextViewDrawable(getDrawableSize(), drawableResId, mCanvasModeTextView);
        mCanvasModeTextView.setText(stringResId);
    }

    /**
     * 更新工具栏笔图标
     *
     * @param penType 颜色值
     * @param index 颜色值下标
     */
    public void checkPenTypeItem(int penType, int index) {
        int[] resArray = MethodUtil.getPenResFromType(penType);
        if (index >= 0 && index < resArray.length) {
            initTextViewDrawable(getDrawableSize(), resArray[index], mPencilTextView);
        }

        if (mPenTypes == null) {
            mPenTypes = getResources().getStringArray(R.array.common_pen_type);
        }

        mPencilTextView.setText(mPenTypes[penType]);
    }

    private void checkTouchModeView() {
        if (mCurrentTouchMode == WhiteBoardTouchMode.TOUCH_MODE_PEN.getValue()) {
            mPencilTextView.setSelected(true);
            mEraserTextView.setSelected(false);
            mSelectTextView.setSelected(false);
        } else if (mCurrentTouchMode == WhiteBoardTouchMode.TOUCH_MODE_ERASER.getValue()) {
            mPencilTextView.setSelected(false);
            mEraserTextView.setSelected(true);
            mSelectTextView.setSelected(false);
        } else if (mCurrentTouchMode == WhiteBoardTouchMode.TOUCH_MODE_SELECT.getValue()) {
            mPencilTextView.setSelected(false);
            mEraserTextView.setSelected(false);
            mSelectTextView.setSelected(true);
        } else {
            LogUtil.error(TAG, "touchMode not available!");
        }
    }

    private void initPenPickerPopWindow() {
        if (mPenPickerPopWindow == null) {
            mPenPickerPopWindow = new PenPickerPopWindow(getContext());
            mPenPickerPopWindow.setPenChildMenuList((color, penType) -> {
                mCurrentPenType = penType;
                mCurrentPenColor = color;
                if (mCallback != null) {
                    mCallback.onSelectPen(color, penType);
                }
            });
        }
    }

    /**
     * 橡皮擦选择器
     *
     * @param view view
     */
    public void showEraserPopWindow(View view) {
        updateCheckedTouchMode(WhiteBoardTouchMode.TOUCH_MODE_ERASER.getValue());
        if (mEraserPickerPopWindow == null) {
            initEraserPickerPopWindow();
        }
        mEraserPickerPopWindow.show(view, ToolbarPosition.BOTTOM);
    }

    private void initEraserPickerPopWindow() {
        mEraserPickerPopWindow = new EraserPickerPopWindow(getContext());
        mEraserPickerPopWindow.setOnEraserPickerListener(new EraserPickerPopWindow.OnEraserPickerListener() {
            @Override
            public void onEraserPicker(int eraser) {
            }

            @Override
            public void onEraserClear() {
                if (mCallback != null) {
                    mCallback.onClearScreen();
                }
            }
        });
    }

    /**
     * 设置 popwindow
     *
     * @param view view
     */
    public void showSettingPickerPopWindow(View view) {
        if (mSettingPickerPopWindow == null) {
            initSettingPickerPopWindow();
        }
        mSettingPickerPopWindow.updateChecked(mCurrentCanvasBgColor);
        mSettingPickerPopWindow.show(view, ToolbarPosition.BOTTOM_END);
    }

    private void initSettingPickerPopWindow() {
        mSettingPickerPopWindow =
            new SettingPickerPopWindow(getContext(), LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, true);
        mSettingPickerPopWindow.setOnWbBackgroundColorListener(color -> {
            if (color == mCurrentCanvasBgColor) {
                return;
            }
            mCallback.onSelectBackgroundColor(color);
            mCurrentCanvasBgColor = color;
            if (color == Constant.CANVAS_BACKGROUND_COLOR_WHITE_RGBA) {
                mWhitePenColorImage.setImageResource(R.drawable.selector_toolbar_pen_black);
            } else {
                mWhitePenColorImage.setImageResource(R.drawable.selector_toolbar_pen_white);
            }
        });
    }

    private void updatePageIndicatorImage(int current, int total) {
        mNewPageImage.setEnabled(total != Constant.MAX_PAGE_COUNT);

        if (current == 1) {
            mPreImage.setEnabled(false);
            mNextImage.setEnabled(total != 1);
        } else {
            mPreImage.setEnabled(true);
            mNextImage.setEnabled(total != current);
        }
    }

    /**
     * 获取画布背景颜色
     *
     * @return 画布背景颜色
     */
    public int getCurrentCanvasBgColor() {
        return mCurrentCanvasBgColor;
    }

    /**
     * ClickCallback 点击事件回调接口
     *
     * @since 2020-01-01
     */
    public interface ClickCallback {

        /**
         * 选择笔
         *
         * @param color 笔颜色
         * @param type 类型
         */
        void onSelectPen(int color, int type);

        /**
         * 清屏
         */
        void onClearScreen();

        /**
         * 设置背景颜色
         *
         * @param color color
         */
        void onSelectBackgroundColor(int color);
    }
}
